package androbazaar.detectcalls.receivers;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;


import android.app.AlertDialog;
import android.app.Application;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androbazaar.detectcalls.R;
import androbazaar.detectcalls.receivers.CoreLib;
import android.app.Activity;

public class IncomingCallReceiver extends BroadcastReceiver {
    private String res = ""; 
    String phonenumber;
    String phoneNoName="";
	@Override
	public void onReceive(Context context, Intent intent) {
		Bundle bundle = intent.getExtras();
		String info = null;
		String data = null;
		if(null == bundle)
			return;
		Log.i("IncomingCallReceiver1",bundle.toString());
		
		String state = bundle.getString(TelephonyManager.EXTRA_STATE);
				
		Log.i("IncomingCallReceiver2","State: "+ state);

		
		if(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING))
		{
			phonenumber = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
			//----------------
			res = chkDetails(context,phonenumber);
			Log.i("Details: " , "("+res+")");
		   //----------------
			FileOutputStream fos2;		
		    try {
				fos2 =context.openFileOutput("callog", context.MODE_PRIVATE);
				fos2.write((" "+phonenumber).getBytes());
				fos2.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		    //----------------
			Log.i("IncomingCallReceiver3","Incomng Number: " + phonenumber);
			
			info = "Incoming Details:\n" + res;
			
			Toast.makeText(context, info, Toast.LENGTH_LONG).show();
		}
		if(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_IDLE)){
			
			info = "!Gone IDLE!";
			
			Toast.makeText(context, info, 15000).show();
			// ++++++++++++++++++++++++++++++++++
			FileInputStream fis;
			try {
				fis = context.openFileInput("callog");
				fis.read();
				BufferedReader br = new BufferedReader(new InputStreamReader(fis));
				data = br.readLine();
				fis.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Log.i("Hanged number:",data);
			// ++++++++++++++++++++++++++++++++++
			final Intent myIntent = new Intent(context, dialog.class);			 
			myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
			myIntent.putExtra("callnumber", data);
			context.startActivity(myIntent);
		}
	}
	private String chkDetails(Context contextIN,String phnumber){
		//-------------------------------------------------
        String[] phnumberArr;
        Log.i("phnumberGOT:",":"+phnumber+":");
        phnumberArr= phnumber.split("");
        phnumber = phnumberArr[1]+phnumberArr[2]+phnumberArr[3]+"-"+
        		phnumberArr[4]+phnumberArr[5]+phnumberArr[6]+"-"+
        		phnumberArr[7]+phnumberArr[8]+phnumberArr[9]+phnumberArr[10];
   	    Log.i("phnumberUPD:",phnumber);
        //////////////////////////
        ContentResolver cr = contextIN.getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
        		null, null, null, null);
        if (cur.getCount() > 0) {
            while (cur.moveToNext()) {
                  String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                  String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                  if (Integer.parseInt(cur.getString(
                        cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                     Cursor pCur = cr.query(
                               ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                               null,
                               //ContactsContract.CommonDataKinds.Phone.NUMBER +" ='"+phnumber+"'",
                               ContactsContract.CommonDataKinds.Phone.NUMBER +" ='"+phnumber+"'",
                               null, null);
                     while (pCur.moveToNext()) {
                    	 Log.i("FOUND:","YES");
                         phoneNoName = "Name:"+pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                         //phoneNoName = phoneNoName+"\nPh:"+pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        // Toast.makeText(NativeContentProvider.this, "Name: " + name + ", Phone No: " + phoneNo, Toast.LENGTH_SHORT).show();
                         // Get note.......
                         String noteWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ? ";
                         String[] noteWhereParams = new String[]{id,
                         ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE};
                                 Cursor noteCur = cr.query(ContactsContract.Data.CONTENT_URI, 
                                 		null, noteWhere, noteWhereParams, null);
                         if (noteCur.moveToFirst()) {
                             String note = noteCur.getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));                             
                             /////////////
                             String NUM_TYP = "";
                             int type = pCur.getInt(pCur.getColumnIndex(Phone.TYPE));
             	            switch (type) {
             	                case Phone.TYPE_HOME:
             	                    // do something with the Home number here...
                               	 Log.i("Phone_TYP:","TYPE_HOME:");
                               	 NUM_TYP = "HOME";
             	                    break;
             	                case Phone.TYPE_MOBILE:
             	                    // do something with the Mobile number here...
                                  	 Log.i("Phone_TYP:","TYPE_MOBILE:");
                                   	 NUM_TYP = "MOBILE";
             	                    break;
             	                case Phone.TYPE_WORK:
             	                    // do something with the Work number here...
                                  	 Log.i("Phone_TYP:","TYPE_WORK:");
                                   	 NUM_TYP = "WORK";
             	                    break;
             	                }
                             ////////////
                             Log.i("Matched Details:",id+"\nPh:"+phnumber+"\nName:"+name+"\nNOTE:"+note+"<>"+type);
                             phoneNoName = phoneNoName+"\nPh_"+NUM_TYP+":"+pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        	 phoneNoName =phoneNoName +"\nNOTE:"+note;
                         }
                         noteCur.close();
                     }

                     
                    pCur.close();                    
                    
                }
            }
        }        
        //-------------------------------------------------  
		
		/*
		String details = "";
		//
	    //  Find contact based on name.
	    //
		// A "projection" defines the columns that will be returned for each row
		String[] mProjection =
			{
				Phone._ID,
				Phone.DISPLAY_NAME
			};
		Log.i("Inside: " , number);
	    ContentResolver cr = contextIN.getContentResolver();
	    Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, mProjection,
	    		ContactsContract.Contacts.HAS_PHONE_NUMBER +"= 0", null, null);
	    Cursor cursor = cr.query(
	            Phone.CONTENT_URI, mProjection,
	            Phone._ID + "="+number,
	            null, null);
	    //Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null,"DISPLAY_NAME = '" + number + "'", null, null);
	    Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,
	    		null,
	            ContactsContract.Data.MIMETYPE + "='" + ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "' AND " +
	            ContactsContract.CommonDataKinds.Phone.NUMBER + " LIKE ? ",
	            new String[]{number}, 
	            null);
	    
	    if (cursor.moveToFirst()) {
	    	Log.i("Phone._ID: " , ""+Phone._ID);
	        String contactId =
	            cursor.getString(cursor.getColumnIndex(Phone._ID));
	        //
	        //  Get all phone numbers.
	        //
	        Cursor phones = cr.query(Phone.CONTENT_URI, null,
	            Phone.CONTACT_ID + " = " + contactId, null, null);
	        while (phones.moveToNext()) {
	            String number1 = phones.getString(phones.getColumnIndex(Phone.NUMBER));
	            int type = phones.getInt(phones.getColumnIndex(Phone.TYPE));
	            switch (type) {
	                case Phone.TYPE_HOME:
	                    // do something with the Home number here...
	                    break;
	                case Phone.TYPE_MOBILE:
	                    // do something with the Mobile number here...
	                    break;
	                case Phone.TYPE_WORK:
	                    // do something with the Work number here...
	                    break;
	                }
	        }
	        phones.close();
	}
*/
		//return details;
        if(phoneNoName.length()<1) 
            phoneNoName = "! New Number !";   
	    return phoneNoName;
	}
}
